package com.example.senior_config.config;

import com.example.senior_config.converter.MyMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import java.util.List;

/**
 * @author ljw
 * @description
 * @date 2021/9/7 8:15
 */
@EnableWebMvc
@Configuration
@EnableScheduling
@ComponentScan("com.example.senior_config")
public class MyConfig extends WebMvcConfigurerAdapter {

    /**
     * 内部资源视图解析器
     * @author ljw
     * @date 2021/9/8 7:09
     */
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

    /**
     * 上传文件配置
     * @author ljw
     * @date 2021/9/8 7:27
     */
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(1000000);
        return multipartResolver;
    }

    /**
     * 自定义数据转换
     * @param
     * @author ljw
     * @date 2021/9/9 7:49
     */
    @Bean
    public MyMessageConverter converter() {
        return new MyMessageConverter();
    }

    /**
     * 静态资源映射
     * @param  registry 注册器
     * @author ljw
     * @date 2021/9/8 7:12
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("/index");
        registry.addViewController("/toUpload").setViewName("/upload");
        registry.addViewController("/converter").setViewName("/converter");
        registry.addViewController("/sse").setViewName("/sse");
        registry.addViewController("/async").setViewName("/async");
    }

    /**
     * 扩展添加自定义的 HttpMessageConverter
     * @param
     * @author ljw
     * @date 2021/9/9 7:51
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(converter());
    }


}
